package cn.cimoc.handler;

import cn.cimoc.model.vo.ResultVO;
import com.fasterxml.jackson.databind.ObjectMapper;
import cn.cimoc.constant.ErrorEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author LGZ
 * @date 2021/11/20 20:55
 * <p>
 * 匿名用户访问无权接口的处理
 */
public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        ResultVO reason = new ResultVO(ErrorEnum.UNAUTHORIZED);
        response.getWriter().write(new ObjectMapper().writeValueAsString(reason));
    }
}
